﻿// <copyright file="AccountService.cs" company="DatamineConsulting">
//      Copyright (c) DatamineConsulting.  All rights reserved.
// </copyright>
// <author>Sites, Ryan</author>
namespace Kanz4Kidz.Service
{
    using System;
    using System.Linq;
    using System.Web.Security;
    using GenericRepository.EntityFramework;
    using Kanz4Kidz.BusinessModel;
    using Kanz4Kidz.Common;
    using Kanz4Kidz.DataTransfer.Interface;
    using Kanz4Kidz.ViewModel;
    using Kaz4Kidz.Service.Contract;
    using Microsoft.Practices.Unity;

    /// <summary>
    /// The implementation of a account service.
    /// </summary>
    public class AccountService : IAccountService
    {
        #region Declarations

        /// <summary>
        /// Stores a reference to the _member repository.
        /// </summary>
        private readonly IEntityRepository<Member> _memberRepository;

        /// <summary>
        /// Stores a reference to the _user repository.
        /// </summary>
        private readonly IEntityRepository<vw_aspnet_Users> _userRepository;

        /// <summary>
        /// Stores a reference to the role provider.
        /// </summary>
        private SqlRoleProvider _roleProvider;

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="AccountService"/> class.
        /// </summary>
        /// <param name="memberRepository">The member repository.</param>
        /// <param name="userRepository">The user repository </param>
        public AccountService(IEntityRepository<Member> memberRepository, IEntityRepository<vw_aspnet_Users> userRepository)
        {
            _memberRepository = memberRepository;
            _userRepository = userRepository;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the role provider.
        /// </summary>
        public SqlRoleProvider RoleProvider
        {
            get
            {
                return this._roleProvider ?? (this._roleProvider = new SqlRoleProvider());
            }
        }
        #endregion

        #region Implementation of IAccountService

        /// <summary>
        /// Creates the new user.
        /// </summary>
        /// <param name="viewModel">The view model.</param>
        /// <returns>
        ///   <c>ICreateUserStatus</c>
        /// </returns>
        public ICreateUserStatus CreateNewUser(RegisterViewModel viewModel)
        {
            var resultDto = Ioc.Container.Resolve<ICreateUserStatus>();

            try
            {
                MembershipCreateStatus createStatus;
                Membership.CreateUser(viewModel.Email, viewModel.Password, viewModel.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    var newMemberShipUser = _userRepository.FindBy(u => u.LoweredUserName == viewModel.Email).ToList().FirstOrDefault();

                    // Create Member Record
                    if (newMemberShipUser != null)
                    {
                        var member = new Member
                            {
                                FirstName = viewModel.FirstName,
                                LastName = viewModel.LastName,
                                AspNetUserId = newMemberShipUser.UserId
                            };

                        _memberRepository.Add(member);

                        // Create default member role
                        RoleProvider.AddUsersToRoles(new[] { viewModel.Email }, new[] { "member" });
                    }
                    else
                    {
                        resultDto.ErrorMessages.Add("Could not retrieve newly created member");
                    }

                }

                resultDto.MemberCreateStatus = createStatus;
            }
            catch (Exception e)
            {
                resultDto.ErrorMessages.Add(e.Message);
            }
            
            return resultDto;
        }

        #endregion
    }
}
